package com.lfy.encrypt;

import java.security.MessageDigest;

/**
 * 哈希算法
 * @author 杨
 *
 */
public class HashUtils {


    public HashUtils() {
    }

    public static byte[] hashString(String v) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(v.getBytes("utf-8"));
        byte[] bytes = md.digest();
        return bytes;
    }

    public static byte[] hashBytes(byte[] bytes) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(bytes);
        byte[] bytes2 = md.digest();
        return bytes2;
    }

    public static boolean verifyHashString(String v, byte[] bytes) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(v.getBytes("utf-8"));
        byte[] bytes2 = md.digest();
        return getHashValue(bytes2).equals(getHashValue(bytes));
    }

    public static boolean verifyHashBytes(byte[] sbytes, byte[] bytes) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(sbytes);
        byte[] bytes2 = md.digest();
        return getHashValue(bytes2).equals(getHashValue(bytes));
    }

    public static String getHashValue(byte[] bytes) {
        String des = "";
        String tmp = null;

        for(int i = 0; i < bytes.length; ++i) {
            tmp = Integer.toHexString(bytes[i] & 255);
            if (tmp.length() == 1) {
                des = des + "0";
            }

            des = des + tmp;
        }

        return des;
    }

    public static byte[] toBytes(String hexString) {
        System.out.println(hexString);
        if (hexString != null && !"".equals(hexString)) {
            int len = hexString.length() / 2;
            byte[] result = new byte[len];

            for(int i = 0; i < len; ++i) {
                result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
            }

            return result;
        } else {
            return null;
        }
    }

}
